package ejb.student;

import java.util.List;
import javax.ejb.Stateless;

import enity.Student;
import javax.annotation.Resource;
import javax.ejb.EJBException;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;

/**
 * Session Bean implementation class studentbean
 */
@SuppressWarnings("restriction")
@Stateless(mappedName = "student")
@TransactionManagement(TransactionManagementType.CONTAINER)
public class studentbean implements studentejb {

	@PersistenceContext(unitName = "em")
	private EntityManager em;
	@Resource(mappedName = "jdbc/studentdatabase")
	DataSource dataSource;

	/**
	 * Default constructor.
	 */
	public studentbean() {
		// TODO Auto-generated constructor stub
		super();
	}

	public boolean addStudent(String name, String address, String email) {
		try {
			Student newstu = new Student();
			newstu.setAddress(address);
			newstu.setName(name);
			newstu.setEmail(email);

			em.persist(newstu);
			// em.refresh(account);
			em.flush();
		} catch (Exception ex) {
			throw new EJBException("addStudent: " + ex.getMessage());
		}
		return true;
	}

	public boolean updateStudent(int studentID, String name, String address,
			String email) {
		// TODO Auto-generated method stub
		try {
			Student updateStu = em.find(Student.class, studentID);
			if (updateStu == null) {
				return false;
			}
			
			updateStu.setAddress(address);
			updateStu.setName(name);
			updateStu.setEmail(email);
			
			em.merge(updateStu);
		} catch (Exception ex) {
			// TODO: handle exception
			throw new EJBException("updateStudent: " + ex.getMessage());
		}

		return true;
	}

	@TransactionAttribute(TransactionAttributeType.MANDATORY)
	public boolean deleteStudent(int studentID) {
		// TODO Auto-generated method stub
		try {
			Student delStu = em.find(Student.class, studentID);
			if (delStu == null) {
				return false;
			}
			em.remove(delStu);			
		} catch (Exception ex) {
			// TODO: handle exception
		}
		return true;
	}

	@SuppressWarnings("rawtypes")
	public List<Student> findAllStudent() {
		// TODO Auto-generated method stub
		try {
			return em.createNamedQuery("Student.FindAll").getResultList();

		} catch (Exception ex) {
			throw new EJBException("findAllStudent: " + ex.getMessage());
		}
	}

}
